<template>
  <div>
    <!-- <Form class="my-form" ref="models_update" :model="buffer" :rules="rules" :key="value" inline> -->
    <Form class="my-form" ref="models_update" :model="buffer" :rules="rules" inline>
      <Alert v-if="!value">
        <slot name='vnull'>
          请选择要删除的条目
        </slot>
      </Alert>
      <Spin v-else-if="inLoad" fix size="large"></Spin>
      <div class="my-form-item" v-else>
        <slot :model="buffer">
          {{buffer}}
        </slot>
      </div>
      <div class="btn_box">
        <Button type="primary" @click="commit">提交</Button>
        <Button type="error" @click="cancle">取消</Button>
        <slot name="commit"></slot>
      </div>
    </Form>
  </div>
</template>
<script>
export default {
  name:'deleteForm',
  props: {
    value: {
      desc:'表单默认值',
      type: [Object,String],
    },
    rules: {
      desc:'验证规则，支持 Promise',
      type: Object,
      default: () => {
        return {};
      },
    },
    api: {
      desc:'异步接口集合 { getById:Promise, delById:Promise, }',
      type:Object,
      required:true,
      default: () => {
        return {};
      }
    },
    format: {
      desc:'获取记录后格式化,参数为记录值对象',
      type: Function,
    },
  },
  data() {
    return {
      inLoad: false,
      buffer: {}
    };
  },
  mounted() {
    this.getBuffer();
  },
  methods: {
    getBuffer() {
      this.inLoad = true;
      if (this.value) {
        if(this.api.getById){
          this.api.getById(this.value).then(res => {
            this.inLoad = false;
            this.format && this.format(res);
            this.buffer = res;
          }).catch(err => {
            this.$Message.error("获取失败!");
            this.$emit("fail", this.value);
            this.inLoad = false;
          }); 
        }else{
          this.inLoad = false;
        }
      } else {
        this.inLoad = false;
        this.$Message.error("请选择要删除的条目!");
      }
    },
    commit() {
      this.$refs["models_update"].validate((valid, b, c) => {
        if (valid) {
          this.$Message.success("验证成功!");
          this.inLoad = true;
          this.api.delById({
            model: this.buffer
          }).then(res => {
            this.$Message.success("修改成功!");
            this.$emit("success", res);
            this.inLoad = false;
          }).catch(err => {
            this.$Message.error("修改失败!");
            this.$emit("fail", this.value);
            this.inLoad = false;
          });
        } else {
          this.$Message.error("验证失败!");
          this.$emit("fail", this.value);
        }
      });
    },
    refresh() {
      this.$refs["models_update"].resetFields();
      this.getBuffer();
    },
    cancle() {
      this.$Message.info("取消操作!");
      this.$emit("cancle", this.value);
    }
  }
};
</script>